type WebSocketStatus = "open" | "close" | null;

export class WebSocketClass {
  private url: string;
  private msgCallback: (data: any) => void;
  private name: string;
  private ws: WebSocket | null;
  private status: WebSocketStatus;

  constructor(url: string, msgCallback: (data: any) => void, name: string = "default") {
    this.url = url;
    this.msgCallback = msgCallback;
    this.name = name;
    this.ws = null;
    this.status = null;
  }

  public connect(data?: any): void {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = e => {
      this.status = "open";
      console.log(`${this.name}连接成功`, e);
      if (data !== undefined) {
        return this.ws?.send(data);
      }
    };

    this.ws.onmessage = e => {
      return this.msgCallback(e.data);
    };

    this.ws.onclose = e => {
      this.closeHandle(e);
    };

    this.ws.onerror = e => {
      this.closeHandle(e);
    };
  }

  public sendHandle(data: any): void {
    console.log(`${this.name}发送消息给服务器:`, data);
    this.ws?.send(data);
  }

  private closeHandle(e: any = "err"): void {
    if (this.status !== "close") {
      console.log(`${this.name}断开，重连websocket`, e);
      this.connect();
    } else {
      console.log(`${this.name}websocket手动关闭`);
    }
  }

  public closeMyself(): void {
    console.log(`关闭${this.name}`);
    this.status = "close";
    this.ws?.close();
  }
}
